package org.kiwi.data.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.kiwi.data.DbShardingStrategyHolder;
import org.kiwi.data.ReadWriteSeparationHolder;
import org.kiwi.data.annotation.ReadWrite;
import org.kiwi.data.enums.ReadWriteType;
import org.kiwi.data.lb.LoadBalanceStrategy;
import org.kiwi.data.util.MethodUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * Created by jack on 16/10/19.
 */
public class ReadWriteSeparationInterceptor implements MethodInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReadWriteSeparationInterceptor.class);

    private Map<String, LoadBalanceStrategy<String>> loadBalanceStrategyMap;

    public void setLoadBalanceStrategyMap(Map<String, LoadBalanceStrategy<String>> loadBalanceStrategyMap) {
        Assert.notNull(loadBalanceStrategyMap, "loadBalanceStrategyMap must not be null");

        this.loadBalanceStrategyMap = loadBalanceStrategyMap;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String debugInfo = "[" + invocation.toString() + "]";

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("enter into read/write separation interceptor {}", debugInfo);
        }

        try {
            LoadBalanceStrategy<String> loadBalanceStrategy;
            if (StringUtils.isNotBlank(DbShardingStrategyHolder.getDbGroupName())) {
                loadBalanceStrategy = this.loadBalanceStrategyMap.get(DbShardingStrategyHolder.getDbGroupName());
            } else {
                loadBalanceStrategy = this.loadBalanceStrategyMap.values().iterator().next();
            }

            ReadWrite readWriteAnnotation = MethodUtil.getRealMethod(invocation).getAnnotation(ReadWrite.class);

            if (readWriteAnnotation != null && readWriteAnnotation.type() == ReadWriteType.READ) {
                String readDsBeanName = loadBalanceStrategy.elect();
                if (StringUtils.isBlank(readDsBeanName)) {
                    readDsBeanName = loadBalanceStrategy.getWriteDsBeanName();
                }
                ReadWriteSeparationHolder.setReadWriteDatasourceName(readDsBeanName);
            } else {
                ReadWriteSeparationHolder.setReadWriteDatasourceName(loadBalanceStrategy.getWriteDsBeanName());
            }

            return invocation.proceed();

        } catch (Exception e) {
            LOGGER.error("invoke read/write separation interceptor has some problem.", e);
            throw e;

        } finally {
            ReadWriteSeparationHolder.clear();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("leave from read/write separation interceptor {}", debugInfo);
            }
        }
    }
}
